// 全局公共方法
// 此处第二个参数vm，也就是页面使用的this
const install = (Vue, vm) => {
	// 检查登录状态
	const checkLogin = (e = {}) => {
		if (!vm.isLogin) {
			uni.navigateTo({
				url: '/pages/user/login/login'
			})
			return false
		}
		return true
	}

	// 校验是否是H5页面
	const checkH5 = (url) => {
		const testHttp = vm.$u.test.url(url)
		if (testHttp) {
			return '/pages/h5/h5?url=' + url
		} else {
			return url
		}
	}
	// URL参数转对象
	const paramsToObj = (url) => {
		// 如果是完整URL，包含?号，先通过?号分解
		if (url.indexOf('?') != -1) {
			let arr = url.split('?')[1]
		}
		let arr = url.split('&') //先通过？分解得到？后面的所需字符串，再将其通过&分解开存放在数组里
		let obj = {}
		for (let i of arr) {
			obj[i.split('=')[0]] = i.split('=')[1] //对数组每项用=分解开，=前为对象属性名，=后为属性值
		}
		return obj
	}

	// 刷新当前页面
	const refreshPage = () => {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const path = '/' + currentPage.route + vm.$u.queryParams(currentPage.options)
		if (vm.$u.test.contains(currentPage.route, 'tabbar')) {
			uni.reLaunch({
				url: path,
				fail: (err) => {
					console.log(err)
				}
			})
		} else {
			uni.redirectTo({
				url: path,
				fail: (err) => {
					console.log(err)
				}
			})
		}
	}

	// toast
	const showToast = (data = {}) => {
		if (typeof data == 'string') {
			uni.showToast({
				title: data,
				icon: 'none'
			})
		} else {
			uni.showToast({
				title: data.title,
				icon: data.icon || 'none',
				image: data.image || '',
				mask: data.mask || false,
				position: data.position || 'center',
				duration: data.duration || 1500,
				success: () => {
					setTimeout(() => {
						if (data.back) return uni.navigateBack()
						data.success && data.success()
					}, data.duration || 1500)
				}
			})
		}
	}

	// 单图上传
	const uploadImage = (callback) => {
		uni.chooseImage({
			count: 1,
			success: img => {
				const tempFilePaths = img.tempFilePaths
				uni.uploadFile({
					url: 'xxx.com',
					filePath: tempFilePaths[0],
					name: 'file',
					header: {
						openid: vm.userInfo.openid || ''
					},
					success: res => {
						callback && callback(JSON.parse(res.data))
					}
				})
			}
		})
	}
	
	/**
	 * l_price 是lists表中的 CURRENT_BOND_PRICE 字段
	 * spj 是prices 表中的 spj（收盘价）字段 或其它价钱字段
	 * 由于spj 字段是再泸市中长度是不固定的，所以没办法通过 泸市 除以100，深市 除以1000 的计算方式，
	 * 它市通过接口的 f116 除以 f84 两个字段计算出来的，
	 * 由于当时采集没注意到，没采集到 f116 和 f86字段，所以只能通过lists中的价格来计算 收盘价 
	 */
	const bondPrice = (f, price, isFloor = false) => {
		
		if(!price) return '-';
		
		let type = f.type;

		let num = type == 'SZ' ? 1000:100;
		let priceLen = price.toString().length;
		if(type == 'SH' && priceLen > 5) num = 1000;
		
		let rec = (price / num).toString();
		//运算后没小时，添加一个小数后面统一处理
		if(rec.indexOf('.') < 0) rec = rec+'.0';
		
		let xs = rec.substr(rec.lastIndexOf(".")+1);
		let xsLen = type == 'SZ' ? 3:2;
		const zs = rec.substring(0, rec.indexOf('.'))
		
		let i = xs ? xs.length:0
		for(i; i < xsLen; i++) xs+='0';
		// console.log('xs:','zs:',zs, 'xs:',xs, xsLen,rec,f.SECURITY_NAME_ABBR)
		let r = zs +'.'+ xs;
		return isFloor ? parseFloat(r):r;
	}
	
	const bondDs = (data,type) => {
		
		if(!data) return '-';
		
		let num = data / (type == 'SZ' ? 1000:100);
		let str = num.toString();
		//运算后没小时，添加一个小数后面统一处理
		if(str.indexOf('.') < 0) str = str+'.0';
		
		let xsLen = type == 'SZ' ? 3:2;
		
		let xs = str.substr(str.lastIndexOf(".")+1, xsLen);
		const zs = str.substring(0, str.indexOf('.'))
		
		for(let i = xs.length; i < xsLen; i++) xs+='0';
		
		return zs +'.'+ xs;
	}
	
	const bondCe = (c_e) =>{
		if(!c_e) return '-';
		let len = c_e.toString().length;
		let rec = c_e;
		// console.log(len);
		if(len > 5){
			rec = (c_e / 10000).toFixed(2)+'万';
		}
		
		if(len > 8){
			rec = (c_e / 100000000).toFixed(2)+'亿';
		}
		
		return rec;
	}
	const bondCl = (c_l) => {
		if(!c_l) return '-';
		let len = c_l.toString().length;
		let rec = c_l;
		// console.log(len);
		if(len > 5){
			rec = (c_l / 10000).toFixed(0)+'万';
		}
		
		if(len > 8){
			rec = (c_l / 100000000).toFixed(0)+'亿';
		}
		
		return rec;
	}
	/**
	 * 振幅
	 */
	const bondZf = (f)=>{
		if(!f.options) return '-';
		let maxP = bondPrice(f,f.options.max ? f.options.max:0);
		let minP = bondPrice(f,f.options.min ? f.options.min:0);
		let z_s = bondPrice(f,f.options.z_s ? f.options.z_s:0)
		let rec = (maxP-minP) / z_s * 100;
		return rec.toFixed(2);
	}
	
	/**
	 * 溢价cls
	 * @param {Object} val
	 */
	const redOrGreen = (val)=>{
		let cls = '';
		if(val < 0){ 
			cls = 'green';
		}else if(val > 0){
			cls = 'red'
		}
		return cls;
	}
	
	const priceCls = (f, type)=>{
		let rec = '';
		let z_s = bondPrice(f,f.options && f.options.z_s ? f.options.z_s:0, true);
		let bjNum = null;
		switch (type){
			case 'j_k':
			bjNum = bondPrice(f,f.options && f.options.j_k ? f.options.j_k:0, true);
			break;
			case 'zd':
			bjNum = bondPrice(f, f.options&&f.options?f.options.spj:0, true);
			break;
			case 'min':
			bjNum = bondPrice(f, f.options&&f.options?f.options.min:0, true);
			break
			case 'max':
			bjNum = bondPrice(f, f.options&&f.options?f.options.max:0, true);
			break;
		}
		
		if(bjNum === null) return rec;
		
		return z_s > bjNum ? 'green':'red';
	}
	
	const bkDsCls = (info, type)=>{
		let rec = '';
		let z_s = info.z_s ? info.z_s:0;
		let bjNum = null;
		switch (type){
			case 'ds':
				bjNum = info.bk_ds;
				break;
			case 'jk':
				bjNum = info.j_k;
				break;
			case 'max':
				bjNum = info.max;
				break;
			case 'min':
				bjNum = info.min;
				break;
		}
		
		if(bjNum === null) return rec;
		
		return z_s > bjNum ? 'green':'red';
	}
	
	const bkCode = (bk_code) => {
		let str = bk_code.toString();
		if(str.length < 4) str = '0' + str;
		
		return str;
	}
	
	const getVal = (data, key_str, def="-", cl="")=>{
		
		let rec = def;
		
		rec = data[key_str] !=null ? data[key_str]: def;
		// console.log(key_str,":",rec)
		if(key_str.indexOf('.') > 0) {
			let key = key_str.split(".");
			
			let val = data;
			// console.log(key, data)
			for(let i in key){
				let v = val[key[i]];
				// console.log('ddd:', typeof(v), v, i);
				if(typeof(v) != 'object' && (i+1) < key.length){
					val = def;
					break;
				}else{
					val = val[key[i]];
				}
			}
			
			if(key[1] == 'PAY_INTEREST_DAY' && val){
				let currentDate = new Date(),
					currentTimes = currentDate.getTime(),
					currentY = currentDate.getFullYear(),
					payInterestDay = currentY+'-'+val,
					payInterestDayTimes = new Date(payInterestDay);
				
				if(currentTimes > payInterestDayTimes) payInterestDay = (currentY+1) + '-' + val;
				
				val = payInterestDay;
				
				if(cl == 'day'){
					let xcfxr = new Date(payInterestDay);
					val = (xcfxr - currentTimes) / (24*60*60 * 1000);
					val = val.toFixed() + '天';
				}
			}
			
			rec = val != null  ? val:def;
		}
		
		if(cl && rec != def){
			switch (cl){
				case 'toFixed':
					rec = rec.toFixed(2);
					break;
				case 'date':
					rec = rec.substring(0, rec.indexOf(' '));
					break;
				case 'syqx':
					let expire_date = new Date(rec),
						current_date = new Date().getTime();
					let r = (expire_date - current_date) / (365 * 24*60*60) /1000;
					
					rec = r.toFixed(1);
					
					break;
			}
		}
		
		return rec;
	}
	
	const market = (m_code)=>{
		let market = {"SH":'上交所',"SZ":'深交所'};
		return market[m_code] ? market[m_code]:'-';
	}

	Vue.prototype.$u.func = {
		checkLogin,
		checkH5,
		paramsToObj,
		refreshPage,
		showToast,
		uploadImage,
		bondPrice,
		bondDs,
		bondCe,
		bondCl,
		bondZf,
		redOrGreen,
		priceCls,
		bkCode,
		bkDsCls,
		getVal,
		market
	}
	// 将各个定义的方法，统一放进对象挂载到vm.$u.func(因为vm就是this，也即this.$u.func)下
}
export default {
	install
}
